import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime, timedelta


class ApexAnalyzer:


    def __init__(self):
        self.css_styles = """
        <style>
            .main-header {
                font-size: 3rem;
                color: #FF4655;
                text-align: center;
                margin-bottom: 2rem;
                font-weight: bold;
                text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
            }
            .sub-header {
                font-size: 1.8rem;
                color: #FF4655;
                margin-top: 2rem;
                margin-bottom: 1rem;
            }
            .stats-table {
                background-color: rgba(0, 0, 0, 0.1);
                border-radius: 10px;
                padding: 15px;
            }
            .highlight {
                background-color: rgba(255, 70, 85, 0.2);
                border-radius: 5px;
                padding: 2px 5px;
            }
        </style>
        """


        if 'matches' not in st.session_state:
            st.session_state.matches = pd.DataFrame(columns=[
                '时间', '角色', '击杀', '助攻', '救助', '存活时长(秒)', '加分'
            ])

    def generate_sample_data(self):
        return pd.DataFrame({
            '时间': [datetime.now() - timedelta(days=i) for i in range(30)],
            '角色': np.random.choice(['Wraith', 'Bloodhound', 'Pathfinder', 'Gibraltar', 'Lifeline', 'Bangalore'], 30),
            '击杀': np.random.randint(0, 10, 30),
            '助攻': np.random.randint(0, 5, 30),
            '救助': np.random.randint(0, 3, 30),
            '存活时长(秒)': np.random.randint(60, 1200, 30),
            '加分': np.random.randint(0, 100, 30)
        })

    def setup_sidebar(self):
        st.sidebar.title("导航菜单")
        st.sidebar.markdown("---")
        page = st.sidebar.radio("选择页面", ["加分分析", "数据管理"])
        st.sidebar.markdown("---")

        # 数据管理选项
        if page == "数据管理":
            st.sidebar.subheader("数据操作")
            if st.sidebar.button("生成随机数据"):
                st.session_state.matches = self.generate_sample_data()
                st.sidebar.success("已生成随机数据")

            if st.sidebar.button("清除所有数据"):
                st.session_state.matches = pd.DataFrame(columns=[
                    '时间', '角色', '击杀', '助攻', '救助', '存活时长(秒)', '加分'
                ])
                st.sidebar.success("已清除所有数据！")


            st.sidebar.markdown("---")
            st.sidebar.subheader("导入/导出数据")
            uploaded_file = st.sidebar.file_uploader("上传CSV文件", type=['csv'])
            if uploaded_file is not None:
                try:
                    new_data = pd.read_csv(uploaded_file)
                    expected_columns = ['时间', '角色', '击杀', '助攻', '救助', '存活时长(秒)', '加分']
                    if all(col in new_data.columns for col in expected_columns):
                        st.session_state.matches = pd.concat([st.session_state.matches, new_data], ignore_index=True)
                        st.sidebar.success("数据上传成功！")
                    else:
                        st.sidebar.error(
                            "CSV文件格式不正确！请确保包含以下列：时间、角色、击杀、助攻、救助、存活时长(秒)、加分")
                except Exception as e:
                    st.sidebar.error(f"读取文件时出错: {e}")

            if st.sidebar.download_button(
                    label="导出数据为CSV",
                    data=st.session_state.matches.to_csv(index=False).encode('utf-8'),
                    file_name="apex_matches_data.csv",
                    mime="text/csv"
            ):
                st.sidebar.success("数据已准备好下载！")

        return page

    def show_score_analysis(self):
        st.markdown('<h2 class="sub-header">加分趋势分析</h2>', unsafe_allow_html=True)

        if st.session_state.matches.empty:
            st.info("暂无战绩数据，请先在数据管理页面生成或导入数据。")
        else:

            col1, col2 = st.columns(2)
            with col1:
                date_range = st.date_input(
                    "选择日期范围",
                    value=(
                        st.session_state.matches['时间'].min(),
                        st.session_state.matches['时间'].max()
                    ),
                    min_value=st.session_state.matches['时间'].min(),
                    max_value=st.session_state.matches['时间'].max()
                )

            with col2:
                selected_legends = st.multiselect(
                    "筛选角色",
                    options=st.session_state.matches['角色'].unique(),
                    default=st.session_state.matches['角色'].unique()
                )

            # 应用筛选
            filtered_data = st.session_state.matches[
                (st.session_state.matches['时间'].dt.date >= date_range[0]) &
                (st.session_state.matches['时间'].dt.date <= date_range[1]) &
                (st.session_state.matches['角色'].isin(selected_legends))
                ]


            col1, col2, col3, col4 = st.columns(4)
            with col1:
                total_matches = len(filtered_data)
                st.metric("总场次", total_matches)
            with col2:
                avg_kills = filtered_data['击杀'].mean()
                st.metric("场均击杀", f"{avg_kills:.1f}")
            with col3:
                avg_score = filtered_data['加分'].mean()
                st.metric("场均加分", f"{avg_score:.1f}")
            with col4:
                win_rate = len(
                    filtered_data[filtered_data['加分'] > 0]) / total_matches * 100 if total_matches > 0 else 0
                st.metric("上分率", f"{win_rate:.1f}%")

            # 显示数据表格
            st.markdown("### 战绩数据表")
            st.dataframe(
                filtered_data.sort_values('时间', ascending=False),
                use_container_width=True,
                height=300
            )

            # 加分趋势分析
            st.markdown("### 加分趋势分析")

            # 按日期分组计算每日平均加分
            daily_data = filtered_data.copy()
            daily_data['日期'] = daily_data['时间'].dt.date
            daily_avg = daily_data.groupby('日期')['加分'].mean().reset_index()

            # 创建图表
            fig, ax = plt.subplots(figsize=(10, 6))
            ax.plot(daily_avg['日期'], daily_avg['加分'], marker='o', linewidth=2, markersize=6, color='#FF4655')
            ax.set_xlabel('日期')
            ax.set_ylabel('平均加分')
            ax.set_title('每日平均加分趋势')
            ax.grid(True, linestyle='--', alpha=0.7)
            plt.xticks(rotation=45)
            plt.tight_layout()

            st.pyplot(fig)

            # 角色加分对比
            st.markdown("### 角色加分对比")

            legend_stats = filtered_data.groupby('角色')['加分'].mean().round(2)

            col1, col2 = st.columns(2)

            with col1:
                st.dataframe(legend_stats, use_container_width=True)

            with col2:
                fig2, ax2 = plt.subplots(figsize=(8, 6))
                legend_stats.sort_values().plot(kind='barh', ax=ax2, color='#FF4655')
                ax2.set_xlabel('平均加分')
                ax2.set_title('各角色平均加分对比')
                plt.tight_layout()
                st.pyplot(fig2)

    def show_data_management(self):

        st.markdown('<h2 class="sub-header">数据管理</h2>', unsafe_allow_html=True)

        st.info("请使用侧边栏的数据管理功能。您可以在侧边栏生成随机数据、清除数据或导入/导出CSV文件。")

        if not st.session_state.matches.empty:
            st.markdown("### 当前数据概览")
            st.dataframe(st.session_state.matches, use_container_width=True)

            # 数据统计
            col1, col2 = st.columns(2)

            with col1:
                st.markdown("##### 数据基本信息")
                st.write(f"总记录数: {len(st.session_state.matches)}")
                st.write(
                    f"时间范围: {st.session_state.matches['时间'].min().date()} 至 {st.session_state.matches['时间'].max().date()}")
                st.write(f"包含角色: {', '.join(st.session_state.matches['角色'].unique())}")

            with col2:
                st.markdown("##### 数据统计")
                st.write(f"总击杀数: {st.session_state.matches['击杀'].sum()}")
                st.write(f"总加分: {st.session_state.matches['加分'].sum()}")
                st.write(f"平均存活时长: {st.session_state.matches['存活时长(秒)'].mean():.1f} 秒")
        else:
            st.warning("当前没有数据，请使用侧边栏的功能生成或导入数据。")

    def run(self):
        """运行分析应用"""
        # 设置页面布局
        st.set_page_config(
            page_title="Apex Legends 战绩分析",

            layout="wide",
            initial_sidebar_state="expanded"
        )


        st.markdown(self.css_styles, unsafe_allow_html=True)


        st.markdown('<h1 class="main-header">Apex Legends 战绩分析中心</h1>', unsafe_allow_html=True)


        page = self.setup_sidebar()


        if page == "加分分析":
            self.show_score_analysis()
        else:
            self.show_data_management()


